package com.server.llh.llhserverwork.activity.my;

import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.NetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.LlhBaseNFCActivity;
import com.server.llh.llhserverwork.adapter.SpinnerAdapter;
import com.server.llh.llhserverwork.bean.AddressAll;
import com.server.llh.llhserverwork.bean.AllProvinceBean;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.ShiContentData;
import com.server.llh.llhserverwork.receiver.GetCardBroadCast;
import com.server.llh.llhserverwork.utils.Constant;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.utils.ToastTool;
import com.server.llh.llhserverwork.view.CleanableEditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ZTF on 2017-06-06.
 */

public class AddCustomerInfoActivity extends LlhBaseNFCActivity {
    @BindView(R.id.titleName)
    TextView titleName;
    @BindView(R.id.main_back)
    ImageButton mainBack;
    @BindView(R.id.leftBtn_RL_title_base)
    RelativeLayout leftBtnRLTitleBase;
    @BindView(R.id.serverName)
    TextView serverName;
    @BindView(R.id.linearLayout1)
    LinearLayout linearLayout1;
    @BindView(R.id.userCard)
    CleanableEditText userCard;
    @BindView(R.id.layout_card)
    LinearLayout layoutCard;
    @BindView(R.id.userName)
    CleanableEditText userName;
    @BindView(R.id.userphone)
    CleanableEditText userphone;
    @BindView(R.id.userIdCard)
    CleanableEditText userIdCard;
    @BindView(R.id.userName_nicheng)
    CleanableEditText userName_nicheng;
    @BindView(R.id.nan)
    RadioButton nan;
    @BindView(R.id.nv)
    RadioButton nv;
    @BindView(R.id.radioGroup1)
    RadioGroup radioGroup1;
    @BindView(R.id.loginuserName)
    CleanableEditText loginuserName;
    @BindView(R.id.login_userpwd)
    CleanableEditText loginUserpwd;
    @BindView(R.id.address)
    CleanableEditText address;
    @BindView(R.id.select)
    TextView select;
    @BindView(R.id.layout_search)
    LinearLayout layoutSearch;
    @BindView(R.id.shengTxt)
    TextView shengTxt;
    @BindView(R.id.shengSpinner)
    Spinner shengSpinner;
    @BindView(R.id.shiTxt)
    TextView shiTxt;
    @BindView(R.id.shiSpinner)
    Spinner shiSpinner;
    @BindView(R.id.xianTxt)
    TextView xianTxt;
    @BindView(R.id.xianSpinner)
    Spinner xianSpinner;
    private String intentType,mUserId,addressId,shengName,shiName,xianName,addressAll,code;
    long optIdSheng,optIdShi,optIdXian;
    private static final String TAG="AddCustomer";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        titleName.setText("录入信息");

        userId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_ID,
                getApplicationContext());
        userNameStr = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_NAMW,
                getApplicationContext());
        orgId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_ID,
                getApplicationContext());
        orgType = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_TYPE,
                getApplicationContext());
        orgName= SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_NAME,
                getApplicationContext());
        token= SharedPreferenceUtil.getUserInfo(Constants.UserInfo.TOKEN_STR,
                getApplicationContext());
        reqAllProvinceData();
        radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId==R.id.nan){
                    userSex=1;
                }else {
                    userSex=2;
                }
            }
        });
        shengSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                AddressAll addressAll=    addressAllList.get(position);
                optIdSheng= addressAll.getOptId();
                shengName=addressAll.getOptName();
                reqAllCityData(optIdSheng);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        shiSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                AddressAll addressAll=    shiAllList.get(position);
                optIdShi= addressAll.getOptId();
                shiName=addressAll.getOptName();
                reqAllDistrictData(optIdShi);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        xianSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                AddressAll addressAll= xianAllList.get(position);
                optIdXian= addressAll.getOptId();
                xianName=addressAll.getOptName();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }
    GetCardBroadCast getCardBroadCast = null;
    @Override
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.READ_CARDACTION);
        getCardBroadCast = new GetCardBroadCast();
        getCardBroadCast.setmHandler(handler);
        getLbm().registerReceiver(getCardBroadCast, filter);
        super.onResume();
    }

    String cardId;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == -1000) {
                cardId = String.valueOf(msg.obj);
                userCard.setText(""+cardId);
            }
        }
    };
    String userCardStr,userId, orgId,token,orgName,niChengStr, orgType,userNameStr,telephone,userIdCardStr,loginNameStr,loginPwdStr,addressStr;
    int userSex=1;
    @OnClick({R.id.main_back, R.id.layout_search,R.id.select})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.main_back:
                onBackPressed();
                break;
            case R.id.select:
                userCardStr=	userCard.getText().toString();
                userNameStr=userName.getText().toString();
                telephone=userphone.getText().toString();
                loginNameStr=loginuserName.getText().toString();
                loginPwdStr=loginUserpwd .getText().toString();
                addressStr=address.getText().toString();
                userIdCardStr=userIdCard.getText().toString();
                niChengStr=userName_nicheng.getText().toString();
                if (TextUtils.isEmpty(userCardStr)&&TextUtils.isEmpty(userNameStr)&&TextUtils.isEmpty(telephone)&&TextUtils.isEmpty(userIdCardStr)) {
                    ToastTool.showText(getApplicationContext(), "用户信息不全");
                    return;
                }
                String addressAll=shengName+shiName+xianName;
                intSertUser(userCardStr,token,niChengStr,userNameStr,telephone,userIdCardStr,userSex,orgId,orgType,orgName,loginNameStr,loginPwdStr
                        ,addressAll,optIdSheng,shengName,optIdShi,shiName,optIdXian,xianName,addressStr);
                break;
        }
    }

    private void intSertUser(String icNumber,String token,String userNickName,String userName
    ,String contactPhone ,String idNumber ,int userSex ,String originOrgId ,String originOrgType ,String originOrgName,String loginName,
      String loginPassword ,String addressAll,long addressProvinceId ,String addressProvinceName ,long addressCityId,
    String addressCityName,Long addressDistrictId,String addressDistrictName,String addressDetail
    ) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("icNumber", icNumber);
        lRequest.addParam("token", token);
        lRequest.addParam("userNickName", userNickName);
        lRequest.addParam("userName", userName);
        lRequest.addParam("contactPhone", contactPhone);
        lRequest.addParam("userSex", userSex);
        lRequest.addParam("idNumber", idNumber);
        lRequest.addParam("originOrgId", originOrgId);
        lRequest.addParam("originOrgType", originOrgType);
        lRequest.addParam("originOrgName", originOrgName);
        lRequest.addParam("loginName", loginName);
        lRequest.addParam("loginPassword", loginPassword);
        lRequest.addParam("addressAll", addressAll);
        lRequest.addParam("addressProvinceId", addressProvinceId);
        lRequest.addParam("addressProvinceName", addressProvinceName);
        lRequest.addParam("addressCityId", addressCityId);
        lRequest.addParam("addressCityName", addressCityName);
        lRequest.addParam("addressDistrictId", addressDistrictId);
        lRequest.addParam("addressDistrictName", addressDistrictName);
        lRequest.addParam("addressDetail", addressDetail);
        lRequest.setUri(ServerPort.ADD_USER_QUICK);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    T.showAnimErrorToast(AddCustomerInfoActivity.this,"服务器繁忙");
                }
                @Override
                public void onNext(String responseBean,String code) {
                    if (responseBean != null) {
                        Log.d(TAG,"responseBean=="+responseBean);
                        onBackPressed();
                    }else{
                        T.showAnimToast(getApplicationContext(),"用户或卡号已存在！");
                    }
                }
            });
        }

    List<AllProvinceBean.DataBean> dataBeanList=new ArrayList<>();
    AllProvinceBean dataBean=new AllProvinceBean();
    List<AddressAll> addressAllList=new ArrayList<AddressAll>();
    List<AddressAll> shiAllList=new ArrayList<AddressAll>();
    List<AddressAll> xianAllList=new ArrayList<AddressAll>();
    ShiContentData shiContentData=new ShiContentData();
    List<ShiContentData.DataBean> sBeanList=new ArrayList<ShiContentData.DataBean>();

    private void reqAllProvinceData() {
        LRequest lRequest = new LRequest();
        lRequest.addParam("token",token);
        lRequest.setUri(ServerPort.GET_ALL_PROVINCE);
        lRequest.setUriType(UrlsTools.ADDRESS_REQ_URL);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
              T.showAnimErrorToast(AddCustomerInfoActivity.this,"服务器繁忙!");
            }
            @Override
            public void onNext(String responseBean,String code) {
                if (responseBean != null) {
                    dataBean=new Gson().fromJson(responseBean.toString(),AllProvinceBean.class);
                    dataBeanList=dataBean.getData();
                    if (dataBeanList!=null){
                        for (int i=0;i<dataBeanList.size();i++){
                            AddressAll addressAll=new AddressAll();
                            addressAll.setId( dataBeanList.get(i).getId());
                            addressAll.setOptId( dataBeanList.get(i).getProviceId());
                            addressAll.setOptName( dataBeanList.get(i).getProviceName());
                            addressAllList.add(addressAll);
                        }
                        SpinnerAdapter spinnerAdapter=new SpinnerAdapter(getApplicationContext(),addressAllList);
                        shengSpinner.setAdapter(spinnerAdapter);
                    }
                }
            }
        });
    }
    private void reqAllCityData(long provinceId) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("token",token);
        lRequest.addParam("provinceId",provinceId);
        lRequest.setUri(ServerPort.GET_ALL_CITY);
        lRequest.setUriType(UrlsTools.ADDRESS_REQ_URL);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
              T.showAnimErrorToast(AddCustomerInfoActivity.this,"服务器繁忙");
            }
            @Override
            public void onNext(String responseBean,String code) {
                if (responseBean != null) {
                    sBeanList.clear();
                    shiContentData=new Gson().fromJson(responseBean.toString(),ShiContentData.class);
                    sBeanList=shiContentData.getData();
                    if (sBeanList!=null){
                        for (int i=0;i<sBeanList.size();i++){
                            AddressAll addressAll=new AddressAll();
                            addressAll.setId( sBeanList.get(i).getId());
                            addressAll.setOptId( sBeanList.get(i).getCityId());
                            addressAll.setOptName( sBeanList.get(i).getCityName());
                            shiAllList.add(addressAll);
                        }
                        SpinnerAdapter spinnerAdapter=new SpinnerAdapter(getApplicationContext(),shiAllList);
                        shiSpinner.setAdapter(spinnerAdapter);
                    }
                }
            }
        });
    }
    private void reqAllDistrictData(long cityId) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("token",token);
        BigDecimal bd = new BigDecimal(cityId);
        lRequest.addParam("cityId",bd.toPlainString());
        lRequest.setUri(ServerPort.GET_ALL_DISTRICT);
        lRequest.setUriType(UrlsTools.ADDRESS_REQ_URL);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                T.showAnimErrorToast(AddCustomerInfoActivity.this,"服务器繁忙");
            }
            @Override
            public void onNext(String responseBean,String code) {
                if (responseBean != null) {
                    xianAllList.clear();
                    try {
                        JSONObject jsonObject= new JSONObject(responseBean) ;
                        JSONArray jsonArray=jsonObject.getJSONArray("data");
                        for(int i=0;i<jsonArray.length();i++){
                            JSONObject tempJson=jsonArray.getJSONObject(i);
                            AddressAll addressAll=new AddressAll();
                            addressAll.setId( tempJson.getInt("id"));
                            addressAll.setOptId(  tempJson.getInt("countyId"));
                            addressAll.setOptName( tempJson.getString("countyName"));
                            xianAllList.add(addressAll);
                        }
                        SpinnerAdapter spinnerAdapter=new SpinnerAdapter(getApplicationContext(),xianAllList);
                        xianSpinner.setAdapter(spinnerAdapter);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    @Override
    public void showProgress() {
        try{
            showProgress(AddCustomerInfoActivity.this);
        }catch (Exception e){

        }
    }

    @Override
    protected INetRequestManager getRequestManager() {
        return NetRequestManager.getInstance();
    }

    @Override
    public void hideProgress() {
        try{
            closeProgress();
        }catch (Exception e){

        }
    }

    @Override
    protected int getlayout() {
        return R.layout.activity_info_insert;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void doBasess() {

    }
    @Override
    protected void onDestroy() {
        if (getCardBroadCast != null) {
            getLbm().unregisterReceiver(getCardBroadCast);
        }
        super.onDestroy();
    }
}
